#coding:utf-8

import poplib,email
from email.header import decode_header
import smtplib
import time
import os,sys
import re


def sshuserinfo():
    tmpfile = os.popen("who /var/log/wtmp")
    count = 0
    userlist = []
    for line in tmpfile:
        count = count + 1
        userlist.append(line)
    pat = re.compile(r"\((.*)\)")
    valuelist = []
    if count > 0:
        result = pat.search(userlist[count - 1])
        valuelist.append(count)
        ipaddress = result.group(1)
        valuelist.append(ipaddress)
        alist = re.split("\s+",userlist[len(userlist)-1])
        valuelist.append(alist[2])       #时间年月日
        valuelist.append(alist[3])       #时间时分
    return valuelist

def sendmail(val):
    mail_to = smtplib.SMTP('smtp.163.com',25)
    mail_to.login("youremail@163.com","yourpassword")
    msg = """From: likang <youremail@163.com>
To: <youremail@qq.com>
Subject: sshusers added

someone ssh your host ,the user info is:
"""+val[1]+" "+val[2]+" "+val[3]
    mail_to.sendmail('youremail@163.com','youremail@qq.com',msg)
    mail_to.close()

if __name__ == '__main__':
    old_count = 0 
    while 1:
        time.sleep(5)
        val = sshuserinfo()
        if len(val) > 0:
            if val[0] > old_count:
                print "add users"
                sendmail(val)
                old_count = val[0]